package icasue.net.socket.driver.mdc;

import com.alibaba.fastjson.JSON;
import icasue.net.base.annotations.NotNull;
import icasue.net.base.annotations.Nullable;
import icasue.net.protocol.carfun.common.CommandResponse;
import icasue.net.socket.exception.ClientConnectException;
import icasue.net.socket.exception.CommandExecException;
import icasue.net.socket.exception.ProtocolUnSupportException;
import icasue.net.socket.model.register.RegisterInfo;
import icasue.net.socket.thread.SocketProxy;
import icasue.net.socket.utils.Assert;
import icasue.net.protocol.carfun.commands.MDCommand;

import java.util.Map;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/3/19 下午3:36
 * @UpdateDate:
 * @Description:
 */
public class ClientMDCommandDriver implements MDCommandDriver<MDCommand.Client, RegisterInfo> {

    @Override
    public MDCommand.Client[] getSupportCommands() {
        return MDCommand.Client.values();
    }

    @Override
    public CommandResponse<JSON> chooseAndDeal(@NotNull MDCommand.Client command,
                                               @NotNull SocketProxy<RegisterInfo> proxy,
                                               @NotNull Map<String, String> headers,
                                               @Nullable JSON data) throws ProtocolUnSupportException, CommandExecException, ClientConnectException {
        //command socketProxy headers must not be null.
        Assert.notNullAll(command,proxy,headers);
        CommandResponse<JSON> result = null;
        switch (command){
            case CLIENT_CONNECT_END:
                result = doClientConnectEnd(command,proxy,headers,data);
                break;
            default:
                throw new ProtocolUnSupportException("Protocol ["+command.getCommand()+"] UnSupport.");
        }
        return result;
    }

    /**
     * 客户端连接channel连接终止,
     * 立即销毁socket连接，中断输入输出流，
     * 如果当前socket处于channel绑定态，则做channel的clear操作
     * SocketProxy线程资源也被立即回收.
     * @param command
     * @param proxy
     * @param headers
     * @param data
     * @return
     * @throws CommandExecException
     */
    private CommandResponse<JSON> doClientConnectEnd(MDCommand.Client command,
                                                  SocketProxy<RegisterInfo> proxy,
                                                  Map<String, String> headers,
                                                  JSON data) throws ClientConnectException{
        proxy.destroy();
        throw new ClientConnectException("Client Attend Ending Connection...");
    }

}
